//
//  XSJStatusViewModel.swift
//  weiBo项目准备
//
//  Created by 鲜世杰 on 16/5/14.
//  Copyright © 2016年 鲜世杰. All rights reserved.
//

import UIKit

class XSJStatusViewModel: NSObject {
    
    var retweetCountContent: String?
   
    var commentCountContent: String?
   
    var unlikeCountContent: String?
    
    var sourceContent: String?
    var status: XSJStatus?
    var retweetContent : String?
    var mbrankImage : UIImage?
    var verifiedTypeImage: UIImage?
    var timeContent : String? {
    
        
            guard let createAt = status?.created_at else {
            
                return nil
                
            }
            return NSDate.sinaDate(createAt).sinaDateString
//            let dateformater = NSDateFormatter()
//            dateformater.locale = NSLocale(localeIdentifier: "en_US")
//            dateformater.dateFormat = "EEE MMM dd HH:mm:ss z yyyy"
//            let createATdate = dateformater.dateFromString(createAt)
//            
//            if isThisYear(createATdate!)
//            {
//            let calendar = NSCalendar.currentCalendar()
//                if calendar.isDateInToday(createATdate!)
//                {
//            let timeInterval = abs(createATdate!.timeIntervalSinceNow)
//
//                    if timeInterval < 60
//                    {
//                    
//                        return "刚刚"
//                        
//                    }else if timeInterval < 3600{
//                    let result = timeInterval / 60
//                        return "\(Int(result))分钟前"
//                    }else {
//                        
//                        let result = timeInterval / 3600
//                        return "\(Int(result))小时前"
//                        
//                    }
//                    
//                }else if calendar.isDateInYesterday(createATdate!){
//                
//                    dateformater.dateFormat = "昨天 HH:mm"
//                    
//                }else{
//                
//                    dateformater.dateFormat = "MM-dd HH:mm"
//                    
//                }
//                
//                
//            }else{
//            
//                dateformater.dateFormat = "yyyy-MM-dd HH:MM"
//                
//            }
//            
//            return dateformater.stringFromDate(createATdate!)
//        }
        
//    }
    
//    private func isThisYear (createAtDate : NSDate) ->Bool {
//    let currentDate = NSDate()
//        let dateFormatter = NSDateFormatter()
//        dateFormatter.locale = NSLocale(localeIdentifier: "en_US")
//    dateFormatter.dateFormat = "yyyy"
//        let currentDateYear = dateFormatter.stringFromDate(currentDate)
//        let createAtDateYear = dateFormatter.stringFromDate(createAtDate)
//        return currentDateYear == createAtDateYear
//        
    }
    //  原创微博富文本
    var origianlAttributedString: NSAttributedString?
    //  转发微博富文本
    var retweetAttributedString: NSAttributedString?

    init(status: XSJStatus) {
        super.init()
        self.status = status
        handleRetWeetContent(status)
        

        retweetCountContent = handleCountContent(status.reposts_count, defaultTitle: "转发")
        commentCountContent = handleCountContent(status.comments_count, defaultTitle: "评论")
        unlikeCountContent = handleCountContent(status.attitudes_count, defaultTitle: "赞")
        handleSourceContent(status)
        handleMBrankImage(status.user?.mbrank ?? 0)
        handleVerifiedTypeImage(status.user?.verified_type ?? 0)
        origianlAttributedString = handleEmoticonContentWithStatus(status.text!)

    }
    
    
    private func handleEmoticonContentWithStatus(status : String) ->NSAttributedString {
    
        let result = NSMutableAttributedString(string: status)
        
        
        var matchResultArray = [XSJMatchResult]()

        (status as NSString).enumerateStringsMatchedByRegex("\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]") { (captureCount, captureString, captureRange, _) -> Void in
        

            if let emotionStr = captureString.memory as? String {
            
//                let emoticon = XSJEmoticonTools.sharedTools.emoticonWithEmoticonStr(emotionStr)
//                if let emoticon = XSJEmoticonTools.sharedTools.emoticonWithEmoticonStr(emotionStr){
//                
//                    let emoticonAttr = NSAttributedString.attributedWithEmotion(emoticon, font: UIFont.systemFontOfSize(HomeFontSize))
//
//                    result.replaceCharactersInRange(captureRange.memory, withAttributedString: emoticonAttr)
//
//                    
//                }
                let matchResult = XSJMatchResult(string: emotionStr, range: captureRange.memory)
                
                matchResultArray.append(matchResult)

            }
        }
            for value in matchResultArray.reverse() {
                
                if let emoticon = XSJEmoticonTools.sharedTools.emoticonWithEmoticonStr(value.string) {
                    //  创建表情富文本
                    let emoticonAttr = NSAttributedString.attributedWithEmotion(emoticon, font: UIFont.systemFontOfSize(HomeFontSize))
//                    print(status)
                    //  替换表情富文本
                    result.replaceCharactersInRange(value.range, withAttributedString: emoticonAttr)
                    
                }

        }
        
       return result
    }
    
    
    private func handleMBrankImage (count : Int) {
        if count > 0 && count < 7 {
        

            mbrankImage = UIImage(named: "common_icon_membership_level\(count)")
            
        }
        
        
    }
    private func handleRetWeetContent(status : XSJStatus) {
        guard let retweet = status.retweeted_status?.text else {
        
            return
            
        }
        guard let name = status.retweeted_status?.user?.screen_name else {
        
            return
        }
        retweetContent = "@\(name):\(retweet)"
        
        retweetAttributedString = handleEmoticonContentWithStatus(retweetContent!)

        
    }
   
    private func handleCountContent (count : Int, defaultTitle : String) ->String {
        
//        print(count)
        if count > 0{
        
            if count >= 10000 {
            let result = CGFloat (count / 1000 / 10)
                let resultStr = "\(result)万"
                if resultStr.containsString(".0"){
                return resultStr.stringByReplacingOccurrencesOfString(".0" ,withString: "")
                }
                return resultStr
            }else{
            
                return "\(count)"
                
            }
            
        }else{
        
            return defaultTitle
            
        }
        
    }
    private func handleSourceContent(status: XSJStatus) {
        //  判断是否存在
        guard let source = status.source else {
            return
        }
        
        
        
        if source.containsString("\">") {
            let startIndex = source.rangeOfString("\">")?.endIndex
            let endIndex = source.rangeOfString("</")?.startIndex
            
            if let start = startIndex, end = endIndex {
                sourceContent = source.substringWithRange(start..<end)
            }
            
        }
    }
     private func handleVerifiedTypeImage(verified: Int) {
        switch verified {
            
        case 0:
            verifiedTypeImage = UIImage(named: "avatar_vip")
        case 2, 3, 5:
            verifiedTypeImage = UIImage(named: "avatar_enterprise_vip")
        case 220:
            verifiedTypeImage = UIImage(named: "avatar_grassroot")
        default:
            verifiedTypeImage = nil
        }
        
    
    }
}
